package cn.fl.mcr.service.impl;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.service.IMcrLgsUsrService;
import cn.fl.mcr.vo.McrCustomerExportVO;
import cn.fl.mcr.vo.McrCustomerVO;
import cn.fl.spl.utils.FileUtil;
import cn.lb.framework.poi.excel.ExcelExportUtil;
import cn.lb.framework.poi.excel.ExcelImportUtil;
import cn.lb.framework.poi.excel.entity.ImportParams;
import cn.lb.framework.poi.excel.entity.TemplateExportParams;
import cn.lb.framework.poi.excel.entity.enmus.ExcelStyleType;
import cn.lionbridgecapital.loan.model.base.constant.BaseConstant;
import cn.lionbridgecapital.loan.model.utils.CollectionUtils;
import cn.lionbridgecapital.loan.model.utils.StringUtils;
import cn.lionbridgecapital.loan.utils.BaseLogUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.constant.facade.framework.constant.SystemConstant;
import fl.customer.facade.customer.api.ICustomerApiService;
import fl.customer.facade.customer.api.ICustomerQueryApiService;
import fl.customer.facade.customer.condition.CstNpBscInfoQueryCondition;
import fl.customer.facade.customer.dto.CstNpBscInfoDTO;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @Author: YangXin
 * @Description: 物流小贷Service实现层
 * @CreateTime: 2019/12/10 16:49
 * @Version: 1.0.0
 */
@Service
public class McrLgsUsrServiceImpl implements IMcrLgsUsrService {

    private static  final Logger logger = LoggerFactory.getLogger(McrLgsUsrServiceImpl.class);

    @Autowired
    private ISysUsrApiService sysUsrApiService;
    @Autowired
    private ICustomerQueryApiService customerQueryApiService;
    @Autowired
    private ICustomerApiService customerApiService;

    /**
     * 文件临时地址获取附件信息
     * @param realPath 文件路径
     * @return File
     * @throws BaseException 业务流异常
     */
    @Override
    public DataResultVO importData(String realPath) throws BaseException {
        final String methodName = "getCustomerFile";
        if (StringUtils.isEmpty(realPath)){
            BaseLogUtils.error(logger,methodName,"获取附件信息.参数为空");
            throw new BaseException(BaseExceptionConstant.COMMON_0002,"参数为空");
        }
        DataResultVO resultVO = new DataResultVO(BaseConstant.IS_YESNO_YES,"获取附件信息成功");

        FileOutputStream fos = null;
        List<McrCustomerExportVO> mcrCustomerList = null;
        String serverFilePath = "";
        try {
            //读取excel 文件
            List<McrCustomerVO> mcrCustomerVOList = this.importXls(realPath);
            if (CollectionUtils.isEmpty(mcrCustomerVOList) || mcrCustomerVOList.size() == 0){
                BaseLogUtils.info(logger,methodName,"小贷获取附件信息.excel未获取到参数");
                resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                resultVO.setInfo("未获取到参数");
                return resultVO;
            }
            // 获取客户及用户信息
            mcrCustomerList = this.getCustomerAndUserInfo(mcrCustomerVOList);
            // 下载客户信息
            //将数据存入模板
            Map<String,Object> outMap = new HashMap<>();
            outMap.put("mcrCustomerList", mcrCustomerList);
            String tempPath = FileUtil.getSavePath("/template/mcr/mcrCustomerTemp.xlsx");
            TemplateExportParams params = new TemplateExportParams(tempPath, false, "小贷客户信息下载");
            params.setHeadingRows(0);
            params.setHeadingStartRow(1);
            params.setStyle(ExcelStyleType.BORDER.getClazz());
            params.setColForEach(true);// 注：包含遍历list

            String filePath = "mcrCustomerList/";
            serverFilePath = FileUtil.getServerFilePath(filePath);
            serverFilePath = serverFilePath + "MCR" + DateUtils.formatDateToString(new Date(), DateUtils.YYYYMMDDHHMMSS)
                    + ".xlsx";
            BaseLogUtils.info(logger, methodName, "导出小贷客户信息记录=" + serverFilePath);

            //开始下载
            BaseLogUtils.info(logger,methodName,"获取附件信息.param："+JSONObject.toJSONString(outMap));
            Workbook book = ExcelExportUtil.exportExcel(params, outMap);
            fos = new FileOutputStream(serverFilePath);
            book.write(fos);
            fos.flush();
            BaseLogUtils.info(logger,methodName,"获取附件信息.excel写入完毕:");
        }catch (BaseException ex){
            BaseLogUtils.error(logger,methodName,"获取附件信息.异常.ex:"+ex.getMessage(),ex);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo(ex.getMessage());
        }catch (Exception ex){
            BaseLogUtils.error(logger,methodName,"获取附件信息.异常.ex:"+ex.getMessage(),ex);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo("获取附件信息异常");
        } finally {
                try {
                    if (null != fos) {
                        fos.close();
                    }
                } catch (IOException e) {
                   BaseLogUtils.error(logger, "-", "异常", e);
                }
        }
        Map<String,Object> rstMap = new HashMap<>();
        rstMap.put("filePath", serverFilePath);
        rstMap.put("mcrCustomerList", mcrCustomerList);
        resultVO.setData(rstMap);
        BaseLogUtils.info(logger,methodName,"获取附件信息.返回信息:"+JSONObject.toJSONString(resultVO));
        return resultVO;
    }

    /**
     * 获取客户 用户 数据信息
     * @param mcrCustomerVOList 导入客户数据
     * @return 导入客户数据（完善后）
     * @throws BaseException 业务异常
     */
    private List<McrCustomerExportVO> getCustomerAndUserInfo(List<McrCustomerVO> mcrCustomerVOList)throws BaseException{
        final String methodName = "getCustomerAndUserInfo";
        List<McrCustomerExportVO> resultList = new ArrayList<>();
        try {
            for (McrCustomerVO mcrCustomerVO : mcrCustomerVOList) {
                String mobile = mcrCustomerVO.getMobile();
                SysUsrQueryCondition sysUsrQueryCondition = new SysUsrQueryCondition();
                if (StringUtils.isNotEmpty(mobile)) {
                    // 查询用户信息
                    sysUsrQueryCondition.setUsrNm(mobile);
                    sysUsrQueryCondition.setSysCd(PropertiesCacheUtils.getProperty(SystemConstant.FL_SERVICE_CD));
                    sysUsrQueryCondition.setOrgCd(PropertiesCacheUtils.getProperty(SystemConstant.FL_ORG_CD));
                    List<SysUsrDTO> sysUsrDTOS = sysUsrApiService.searchSysUsrList(sysUsrQueryCondition);
                    if (CollectionUtils.isNotEmpty(sysUsrDTOS)) {
                        SysUsrDTO sysUsrDTO = sysUsrDTOS.get(0);
                        mcrCustomerVO.setUsrId(sysUsrDTO.getId());
                        mcrCustomerVO.setName(sysUsrDTO.getRefRlNm());
                    }

                    // 查询客户信息
                    CstNpBscInfoQueryCondition cstNpBscInfoQueryCondition = new CstNpBscInfoQueryCondition();
                    cstNpBscInfoQueryCondition.setMp1(mobile);
                    cstNpBscInfoQueryCondition.setSysCd(PropertiesCacheUtils.getProperty(SystemConstant.FL_SERVICE_CD));
                    cstNpBscInfoQueryCondition.setOrgCd(PropertiesCacheUtils.getProperty(SystemConstant.FL_ORG_CD));
                    List<CstNpBscInfoDTO> cstNpBscInfoDTOS = this.customerApiService.searchCstNpBscInfoWithMp(cstNpBscInfoQueryCondition);
                    if (CollectionUtils.isNotEmpty(cstNpBscInfoDTOS)) {
                        CstNpBscInfoDTO cstNpBscInfoDTO = cstNpBscInfoDTOS.get(0);
                        mcrCustomerVO.setCstId(cstNpBscInfoDTO.getId());
                    }
                }

                McrCustomerExportVO mcrCustomerExportVO = new McrCustomerExportVO();
                mcrCustomerExportVO.setCertNo(mcrCustomerVO.getCertNo());
                mcrCustomerExportVO.setCstId(mcrCustomerVO.getCstId());
                mcrCustomerExportVO.setUsrId(mcrCustomerVO.getUsrId());
                mcrCustomerExportVO.setMobile(mcrCustomerVO.getMobile());
                mcrCustomerExportVO.setName(mcrCustomerVO.getName());
                resultList.add(mcrCustomerExportVO);
            }
        }catch (BaseException ex){
            BaseLogUtils.error(logger,methodName,"导入客户数据获取客户信息.异常.ex:"+ex.getMessage(),ex);
            throw new BaseException(BaseExceptionConstant.COMMON_0002,ex.getMessage());
        }catch (Exception ex){
            BaseLogUtils.error(logger,methodName,"导入客户数据获取客户信息.异常.ex:"+ex.getMessage(),ex);
            throw new BaseException(BaseExceptionConstant.COMMON_0002,"获取客户信息异常");
        }
        return resultList;
    }

    /**
     * 获取Excel文件
     * @param filePath 文件地址
     * @return 文件参数
     * @throws BaseException 业务数据
     */
    private List<McrCustomerVO> importXls(String filePath) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "importXls", "小贷系统导入Excel：realPath:"+filePath, CurrentThreadContext.getCurrentUserName());
        ImportParams params = new ImportParams();
        params.setTitleRows(1);//标题占用行数
        params.setHeadRows(1);//表头占用行数
        params.setNeedSave(false);//是否保存文件

        List<McrCustomerVO> list = null;
        File file = new File(filePath);
        if (file.exists()) {
            BaseLogUtils.info(logger, "importXls", "小贷系统导入Excel.文件存在");
            list = ExcelImportUtil.importExcel(file, McrCustomerVO.class, params);
        }
        BaseLogUtils.info(logger, "importXls", "小贷系统导入Excel:" + JSON.toJSONString(list));
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "importXls", "导入帐号.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return list;
    }
}
